//
//  GPSRecordTableViewController.swift
//  DaFit
//
//  Created by Paul on 2022/1/4.
//  Copyright © 2022 sylar. All rights reserved.
//

import UIKit
import MapKit
import MYModule

open class GPSTrainingRecordTableViewController: ViewController, UITableViewDataSource, UITableViewDelegate {
    
    
    public var type = TrainingType.unknown
    
    open var gpsModel: GPSTrainingModel? {
        
        didSet {
            
            guard let gpsModel = gpsModel else {
                return
            }
            
            mapModel = GPSTrainingMapModel(gpsTrainingModel: gpsModel)
            
            if gpsModel.type == 32 {
                if cells.contains("stepCell") {
                    cells.removeAll("stepCell")
                }
            }
           
            self.tableView.reloadData()
            
        }
        
    }
    
    /// 目标是否达成
    public var achievement: Bool = false
    
    private var mapModel: GPSTrainingMapModel?
    
    public var isfromMapView: Bool = false
    public let tableView = UITableView(frame: CGRect.zero, style: .plain)
    public var cells:[String] = ["mapCell","InfoCell","heartChartCell","heartZoneCell","stepCell"]
    
    
    open override func viewDidLoad() {
        super.viewDidLoad()
        
        
        if achievement == true {
            
            BluetoothResponder.shared.trainingGoalAlert(type: .gpsTrainingGoal)
            
        }
        
    }
    
    open override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    open override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
    }
    
    
    open override func makeUI(){
        
        self.navigation.bar.alpha = 0
        self.navigation.bar.barTintColor = UIColor.background
        self.view.backgroundColor = UIColor.background
        tableView.backgroundColor = UIColor.background
        
        tableView.estimatedRowHeight = UITableView.automaticDimension
        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedSectionHeaderHeight = 0
        tableView.estimatedSectionFooterHeight = 0
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        self.tableView.bounces = false
        self.tableView.tableFooterView = UIView(frame: CGRect.zero)
        
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        }
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        } else {
            self.automaticallyAdjustsScrollViewInsets = false
        }
        
        tableView.register(GPSTrainingMapTableViewCell.self, forCellReuseIdentifier: NSStringFromClass(GPSTrainingMapTableViewCell.self))
        tableView.register(GPSTrainingInfoTableViewCell.self, forCellReuseIdentifier: NSStringFromClass(GPSTrainingInfoTableViewCell.self))
        tableView.register(GPSTrainingHeartChartTableViewCell.self, forCellReuseIdentifier: NSStringFromClass(GPSTrainingHeartChartTableViewCell.self))
        tableView.register(GPSTrainingHeartZoneTableViewCell.self, forCellReuseIdentifier: NSStringFromClass(GPSTrainingHeartZoneTableViewCell.self))
        tableView.register(GPSTrainingStepTableViewCell.self, forCellReuseIdentifier: NSStringFromClass(GPSTrainingStepTableViewCell.self))
        
        tableView.dataSource = self
        tableView.delegate = self
        view.addSubview(tableView)
        
        tableView.snp.makeConstraints { make in
            make.left.right.top.bottom.equalToSuperview()
        }
        
    }
    

    
    //MARK: - 返回按钮
    open override func backAction() {

        for controller in self.navigationController!.viewControllers where controller is TrainingRecordsController {
            self.navigationController?.popViewController(animated: true)
            return
        }
        
        for controller in self.navigationController!.viewControllers where controller is ActivityHomeController {
            self.navigationController?.popViewController(animated: true)
            return
        }
        
        self.navigationController?.popToRootViewController(animated: true)
    }
    
    // MARK: - Table view data source
    
    open func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }
    
    open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return cells.count
    }
    
    open func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0
    }
    
    open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let row = indexPath.row
        
        if row > self.cells.count - 1{
            return UITableViewCell()
        }
        let cellName = self.cells[row]
        switch cellName{
        case "mapCell":
            let cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(GPSTrainingMapTableViewCell.self), for: indexPath) as! GPSTrainingMapTableViewCell
            
            cell.mapModel = mapModel
            
            return cell
        case "InfoCell":
            
            let cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(GPSTrainingInfoTableViewCell.self), for: indexPath) as! GPSTrainingInfoTableViewCell
            setUpInfoCell(cell: cell)
            return cell
        case "heartChartCell":
            let cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(GPSTrainingHeartChartTableViewCell.self), for: indexPath) as! GPSTrainingHeartChartTableViewCell
            
            cell.trainingModel = gpsModel
            
            return cell
        case "heartZoneCell":
            let cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(GPSTrainingHeartZoneTableViewCell.self), for: indexPath) as! GPSTrainingHeartZoneTableViewCell
            //TODO: 单元测试
//            cell.times = [3500, 40, 0, 0, 0]
            cell.hearts = gpsModel?.heartRates
            return cell
        case "stepCell":
            let cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(GPSTrainingStepTableViewCell.self), for: indexPath) as! GPSTrainingStepTableViewCell
            cell.type = type
            
            if let minSteps = gpsModel?.steps, let minDistance = gpsModel?.distances, minSteps.count == minDistance.count {
                var rates:[Double] = []
                var strides:[Double] = []
                for i in 0..<minSteps.count{
                    let step = Double(minSteps[i])
                    let distance = minDistance[i]
                    var stride:Double = 0.0
                    if step > 0{
                        stride = Double(distance)/step
                    }
                    rates.append(step)
                    strides.append(stride)
                }
                cell.rate = rates
                cell.stride = strides
            }
            
            if let route = gpsModel {
                
                let start = Date(timeIntervalSince1970: TimeInterval(route.startTime))
                let end = Date(timeIntervalSince1970: TimeInterval(route.endTime))
                cell.setHorizontalStackView(start: start, end: end)
                
            }
            return cell
        default:
            break
        }
        
        return UITableViewCell()
    }
    

    open func setUpInfoCell(cell: GPSTrainingInfoTableViewCell) {
        cell.bindModel(self.gpsModel)
    }
    
}

extension GPSTrainingRecordTableViewController {
    
    public func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        let indexPath = IndexPath(row: 0, section: 0)
        
        guard let cell = tableView.cellForRow(at: indexPath) as? GPSTrainingMapTableViewCell else { return }
        
        let mapHeight = cell.mapView.frame.height
        let top = UIApplication.shared.statusBarFrame.height + self.navigation.bar.height
        let offset = mapHeight - scrollView.contentOffset.y - top
        if offset >= 0 {
            let alpha = 1.0 - offset/top
            //            print(alpha)
            self.navigation.bar.alpha = alpha
            
            if alpha >= 1 {
                self.navigation.item.title = self.type.title
            } else {
                self.navigation.item.title = nil
            }
            
        } else {
            self.navigation.bar.alpha = 1
            
            self.navigation.item.title = self.type.title
        }
 
    }
    
    
}



extension MKMapView  {
//    //缩放级别
//    var zoomLevel:  Int  {
//        //获取缩放级别
//        get {
//            return  Int (log2(360 * ( Double ( self.frame.size.width/256)
//                                      /  self .region.span.longitudeDelta)) + 1)
//        }
//        //设置缩放级别
//        set  (newZoomLevel){
//            setCenterCoordinate(coordinate: self.centerCoordinate, zoomLevel: newZoomLevel,
//                                animated: false)
//        }
//    }
//    
//    //设置缩放级别时调用
//    private func setCenterCoordinate(coordinate:  CLLocationCoordinate2D , zoomLevel:  Int ,
//                                     animated:  Bool ){
//        let  span =  MKCoordinateSpan(latitudeDelta: 0, longitudeDelta: 360 / pow(2,  Double (zoomLevel)) *  Double (self.frame.size.width) / 256)
//        setRegion(MKCoordinateRegion(center: coordinate, span: span), animated: animated)
//        
//    }
}
